import json
import re
import traceback
import logging
from datetime import datetime
from typing import List, Dict, Any

from core.spider.pure_api_zero import ApiZeroSeven

# Configure logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
if not logger.handlers:
    handler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

# 导入MatchDataV2 ORM类
from db.entity2 import MatchDataV2


class FootballMatchParser:
    """解析JavaScript足球比赛数据的类"""

    def __init__(self):
        self.matches = []
        self.leagues = {}
        self.countries = {}

    def parse_js_data(self, js_content: str) -> Dict[str, Any]:
        """
        解析JavaScript数据，提取A、B、C数组
        """
        # 提取A数组（比赛数据）
        a_matches = re.findall(r'A\[\d+\]\s*=\s*"([^"]+)"\.split\(\'\^\'\)', js_content)

        # 提取B数组（赛事分类）
        b_matches = re.findall(r'B\[\d+\]\s*=\s*"([^"]+)"\.split\(\'\^\'\)', js_content)

        # 提取C数组（国家地区）
        c_matches = re.findall(r'C\[\d+\]\s*=\s*\[([^\]]+)\]', js_content)

        return {
            'A': a_matches,
            'B': b_matches,
            'C': c_matches
        }

    def parse_match_data(self, match_string: str) -> Dict[str, Any]:
        """
        解析单场比赛数据
        """
        fields = match_string.split('^')
        errors = []

        # 基础比赛信息
        match_info = {}

        # 获取比赛ID用于日志记录
        match_id = fields[0] if len(fields) > 0 else '未知ID'

        # 对每个字段解析使用独立的try-catch块
        try:
            match_info['match_id'] = match_id
        except Exception as e:
            errors.append(f"match_id字段: {e}")
            match_info['match_id'] = ''

        try:
            match_info['color'] = fields[1] if len(fields) > 1 else ''
        except Exception as e:
            errors.append(f"color字段: {e}")
            match_info['color'] = ''

        try:
            match_info['league_name_simple'] = fields[2] if len(fields) > 2 else ''
        except Exception as e:
            errors.append(f"league_name_simple字段: {e}")
            match_info['league_name_simple'] = ''

        try:
            match_info['league_name_traditional'] = fields[3] if len(fields) > 3 else ''
        except Exception as e:
            errors.append(f"league_name_traditional字段: {e}")
            match_info['league_name_traditional'] = ''

        try:
            home_team_simple = fields[5] if len(fields) > 5 else ''
            home_team_simple = self.clean_match_team_names(home_team_simple)
            match_info['home_team_simple'] = home_team_simple
        except Exception as e:
            errors.append(f"home_team_simple字段: {e}")
            match_info['home_team_simple'] = ''

        try:
            home_team_traditional = fields[6] if len(fields) > 6 else ''
            home_team_traditional = self.clean_match_team_names(home_team_traditional)
            match_info['home_team_traditional'] = home_team_traditional
        except Exception as e:
            errors.append(f"home_team_traditional字段: {e}")
            match_info['home_team_traditional'] = ''

        try:
            away_team_simple = fields[8] if len(fields) > 7 else ''
            away_team_simple = self.clean_match_team_names(away_team_simple)
            match_info['away_team_simple'] = away_team_simple
        except Exception as e:
            errors.append(f"away_team_simple字段: {e}")
            match_info['away_team_simple'] = ''

        try:
            away_team_traditional = fields[9] if len(fields) > 8 else ''
            away_team_traditional = self.clean_match_team_names(away_team_traditional)
            match_info['away_team_traditional'] = away_team_traditional
        except Exception as e:
            errors.append(f"away_team_traditional字段: {e}")
            match_info['away_team_traditional'] = ''

        try:
            match_info['match_time'] = fields[11] if len(fields) > 9 else ''
        except Exception as e:
            errors.append(f"match_time字段: {e}")
            match_info['match_time'] = ''

        try:
            match_info['match_datetime'] = fields[12] if len(fields) > 10 else ''
        except Exception as e:
            errors.append(f"match_datetime字段: {e}")
            match_info['match_datetime'] = ''

        # 添加新的字段解析
        try:
            match_info['match_status'] = int(fields[13]) if len(fields) > 13 and fields[13] else 0
        except Exception as e:
            errors.append(f"match_status字段: {e}")
            match_info['match_status'] = 0

        try:
            match_info['home_score'] = int(fields[14]) if len(fields) > 14 and fields[14] else 0
        except Exception as e:
            errors.append(f"home_score字段: {e}")
            match_info['home_score'] = 0

        try:
            match_info['away_score'] = int(fields[15]) if len(fields) > 15 and fields[15] else 0
        except Exception as e:
            errors.append(f"away_score字段: {e}")
            match_info['away_score'] = 0

        # 字段取值确认 todo
        try:
            match_info['home_half_score'] = int(fields[16]) if len(fields) > 16 and fields[16] else 0
        except Exception as e:
            errors.append(f"home_half_score字段: {e}")
            match_info['home_half_score'] = 0

        # 字段取值确认 todo
        try:
            match_info['away_half_score'] = int(fields[17]) if len(fields) > 17 and fields[17] else 0
        except Exception as e:
            errors.append(f"away_half_score字段: {e}")
            match_info['away_half_score'] = 0


        # 联赛和球队排名信息
        if len(fields) > 16:
            try:
                match_info['home_team_rank'] = fields[16] if fields[16] else ''
            except Exception as e:
                errors.append(f"home_team_rank字段: {e}")
                match_info['home_team_rank'] = ''

            try:
                match_info['away_team_rank'] = fields[17] if len(fields) > 17 and fields[17] else ''
            except Exception as e:
                errors.append(f"away_team_rank字段: {e}")
                match_info['away_team_rank'] = ''

            try:
                match_info['is_neutral'] = fields[18] == '1' if len(fields) > 18 else False
            except Exception as e:
                errors.append(f"is_neutral字段: {e}")
                match_info['is_neutral'] = False

            try:
                match_info['is_hot'] = fields[19] == '1' if len(fields) > 19 else False
            except Exception as e:
                errors.append(f"is_hot字段: {e}")
                match_info['is_hot'] = False

            try:
                match_info['has_live'] = fields[20] == 'True' if len(fields) > 20 else False
            except Exception as e:
                errors.append(f"has_live字段: {e}")
                match_info['has_live'] = False

            try:
                match_info['handicap'] = float(fields[21]) if len(fields) > 21 and fields[21] else 0.0
            except Exception as e:
                errors.append(f"handicap字段: {e}")
                match_info['handicap'] = 0.0

            # 是否滚球
            try:
                match_info['gunqiu'] = fields[28]=="True" if len(fields) > 28 and fields[28] else False
                # if match_info['gunqiu']:
                #     print("滚球"+match_id)
            except Exception as e:
                errors.append(f"gunqiu字段: {e}")
                match_info['gunqiu'] = False

        # 分析推荐信息
        if len(fields) > 37:
            try:
                match_info['analysis_recommend'] = fields[37] if fields[37] else ''
            except Exception as e:
                errors.append(f"analysis_recommend字段: {e}")
                match_info['analysis_recommend'] = ''

        # 如果有错误，一次性记录所有错误信息，包含比赛ID
        if errors:
            logger.warning(f"解析比赛数据(比赛ID: {match_id})时出现{len(errors)}个错误: {', '.join(errors)}")

        return match_info

    def parse_league_data(self, league_string: str) -> Dict[str, Any]:
        """
        解析赛事分类数据
        """
        fields = league_string.split('^')
        errors = []

        league_info = {}

        # 获取联赛相关信息用于日志记录
        league_name = fields[0] if len(fields) > 0 else '未知联赛'

        try:
            league_info['league_name_simple'] = league_name
        except Exception as e:
            errors.append(f"league_name_simple字段: {e}")
            league_info['league_name_simple'] = ''

        try:
            league_info['league_name_traditional'] = fields[1] if len(fields) > 1 else ''
        except Exception as e:
            errors.append(f"league_name_traditional字段: {e}")
            league_info['league_name_traditional'] = ''

        try:
            league_info['league_id'] = fields[3] if len(fields) > 3 else ''
        except Exception as e:
            errors.append(f"league_id字段: {e}")
            league_info['league_id'] = ''

        try:
            league_info['sclass_id'] = fields[4] if len(fields) > 4 else ''
        except Exception as e:
            errors.append(f"sclass_id字段: {e}")
            league_info['sclass_id'] = ''

        # 如果有错误，一次性记录所有错误信息
        if errors:
            logger.warning(f"解析联赛数据(联赛: {league_name})时出现{len(errors)}个错误: {', '.join(errors)}")

        return league_info

    def parse_country_data(self, country_string: str) -> Dict[str, Any]:
        """
        解析国家地区数据
        """
        # 清理字符串并解析数组
        country_string = country_string.replace("'", "").replace('"', '')
        fields = [field.strip() for field in country_string.split(',')]
        errors = []

        country_info = {}

        # 获取国家相关信息用于日志记录
        country_id = fields[0] if len(fields) > 0 else '未知国家'

        try:
            country_info['country_id'] = country_id
        except Exception as e:
            errors.append(f"country_id字段: {e}")
            country_info['country_id'] = ''

        try:
            country_info['country_name_simple'] = fields[1] if len(fields) > 1 else ''
        except Exception as e:
            errors.append(f"country_name_simple字段: {e}")
            country_info['country_name_simple'] = ''

        try:
            country_info['country_name_traditional'] = fields[3] if len(fields) > 3 else ''
        except Exception as e:
            errors.append(f"country_name_traditional字段: {e}")
            country_info['country_name_traditional'] = ''

        # 如果有错误，一次性记录所有错误信息
        if errors:
            logger.warning(f"解析国家数据(国家ID: {country_id})时出现{len(errors)}个错误: {', '.join(errors)}")

        return country_info


    def format_datetime(self, datetime_str: str) -> str:
        """格式化日期时间"""
        if not datetime_str or datetime_str == '-':
            return ''

        try:
            # 处理 "2025,10,13,21,32,20" 格式
            parts = datetime_str.split(',')
            if len(parts) >= 3:
                year, month, day = parts[0], parts[1], parts[2]
                return f"{year}-{month.zfill(2)}-{day.zfill(2)}"
        except Exception as e:
            logger.warning(f"格式化日期时间失败: {e}")

        return datetime_str

    def process_js_content(self, js_content: str) -> Dict[str, Any]:
        """
        处理完整的JS内容，返回结构化的比赛数据
        """
        # 解析JS数据
        parsed_data = self.parse_js_data(js_content)

        # 处理比赛数据
        matches = []
        for i, match_str in enumerate(parsed_data['A']):
            try:
                # # 临时 根据id debug
                # if "2896862" not in match_str :
                #     continue
                match_data = self.parse_match_data(match_str)
                match_data['index'] = i + 1

                # 添加格式化后的信息
                # match_data['status_text'] = self.get_match_status_text(match_data['match_status'])
                match_data['formatted_date'] = self.format_datetime(match_data['match_datetime'])
                # match_data['score'] = f"{match_data['home_score']}-{match_data['away_score']}"
                # match_data['half_score'] = f"{match_data['home_half_score']}-{match_data['away_half_score']}"

                matches.append(match_data)
            except Exception as e:
                traceback.print_exc()
                print(f"解析比赛数据错误 (索引 {i}): {e}")
                continue

        # 处理联赛数据
        leagues = []
        for i, league_str in enumerate(parsed_data['B']):
            try:
                league_data = self.parse_league_data(league_str)
                league_data['index'] = i + 1
                leagues.append(league_data)
            except Exception as e:
                print(f"解析联赛数据错误 (索引 {i}): {e}")
                continue

        # 处理国家数据
        countries = []
        for i, country_str in enumerate(parsed_data['C']):
            try:
                country_data = self.parse_country_data(country_str)
                country_data['index'] = i
                countries.append(country_data)
            except Exception as e:
                print(f"解析国家数据错误 (索引 {i}): {e}")
                continue

        return {
            'matches': matches,
            'leagues': leagues,
            'countries': countries,
            'summary': {
                'total_matches': len(matches),
                'total_leagues': len(leagues),
                'total_countries': len(countries)
            }
        }

    def convert_matches_to_match_data_v2(self, matches_data: List[Dict[str, Any]]) -> List['MatchDataV2']:
        """
        将解析后的比赛数据转换为MatchDataV2 ORM对象列表
        
        Args:
            matches_data: 解析后的比赛数据列表
            
        Returns:
            MatchDataV2对象列表
        """
        converted_matches = []
        
        for match in matches_data:
            try:
                match_v2 = MatchDataV2(
                    比赛ID=match.get('match_id', ''),
                    颜色=match.get('color', ''),
                    联赛名_简体=match.get('league_name_simple', ''),
                    联赛名_繁体=match.get('league_name_traditional', ''),
                    主队名_简体=match.get('home_team_simple', ''),
                    主队名_繁体=match.get('home_team_traditional', ''),
                    客队名_简体=match.get('away_team_simple', ''),
                    客队名_繁体=match.get('away_team_traditional', ''),
                    比赛时间=match.get('match_time', ''),
                    比赛日期时间=match.get('match_datetime', ''),
                    比赛状态=match.get('match_status', 0),
                    主队比分=match.get('home_score', 0),
                    客队比分=match.get('away_score', 0),
                    主队半场比分=match.get('home_half_score', 0),
                    客队半场比分=match.get('away_half_score', 0),
                    主队排名=match.get('home_team_rank', ''),
                    客队排名=match.get('away_team_rank', ''),
                    是否中立场地=match.get('is_neutral', False),
                    是否热门=match.get('is_hot', False),
                    是否走地=match.get('gunqiu', False),
                    是否有直播=match.get('has_live', False),
                    让球数=match.get('handicap', 0.0),
                    分析推荐=match.get('analysis_recommend', '')
                )
                converted_matches.append(match_v2)
            except Exception as e:
                logger.error(f"转换比赛数据时出错 (比赛ID: {match.get('match_id', '未知')}): {e}")
                continue
                
        return converted_matches

    def clean_match_team_names(self, team_name: str) -> str:
        """
        处理球队名称，移除无用符号
        """
        if "<" in team_name:
            # 移除HTML标签，例如"<span>球队名</span>"变为"球队名"
            team_name = re.sub(r'<[^>]+>', '', team_name)
            team_name = team_name.strip()
        return team_name


# 使用示例
if __name__ == "__main__":
    # 创建解析器
    parser = FootballMatchParser()

    # 这里应该是读取JS文件的代码
    # 假设js_content包含您提供的完整JS代码

    # 模拟处理过程 - 实际使用时取消注释下面的代码
    api007 = ApiZeroSeven()
    today_match_bf_data_list = api007.get_today_match_bf_data()
    print(today_match_bf_data_list)
    try:
        with open('../spider/html/bfdata.js', 'r', encoding='utf-8') as f:
            js_content = f.read()

        result = parser.process_js_content(js_content)
        
        # 调用转换方法将解析后的数据转换为MatchDataV2对象
        match_data_v2_list = parser.convert_matches_to_match_data_v2(result['matches'])
        print(f"成功转换 {len(match_data_v2_list)} 条比赛数据为MatchDataV2对象")

        for match_data in match_data_v2_list:
            print(match_data)
        # 打印摘要信息
        print("=" * 50)
        print("足球比赛数据解析结果")
        print("=" * 50)
        print(f"总比赛场次: {result['summary']['total_matches']}")
        print(f"总赛事类型: {result['summary']['total_leagues']}")
        print(f"总国家地区: {result['summary']['total_countries']}")
        print()

        # 显示前5场比赛信息
        print("前5场比赛信息:")
        print("-" * 50)
        for i, match in enumerate(result['matches'][:5]):
            print(json.dumps(match, ensure_ascii=False))

    except Exception as e:
        traceback.print_exc()
        print(f"处理JS数据时出错: {e}")
